package com.sora.service.impl;


import com.benjaminwan.ocrlibrary.OcrResult;
import com.benjaminwan.ocrlibrary.Point;
import com.benjaminwan.ocrlibrary.TextBlock;
import com.sora.result.Result;
import com.sora.service.SystemService;
import io.github.mymonstercat.Model;
import io.github.mymonstercat.ocr.InferenceEngine;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @Classname SystemServiceImpl
 * @Description
 * @Date 2024/07/15 16:15
 * @Author by Sora33
 */
@Service
public class SystemServiceImpl implements SystemService {

    private Logger logger = LoggerFactory.getLogger(SystemServiceImpl.class);

    private final HttpServletResponse response;

    public SystemServiceImpl(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public Result ocr(MultipartFile multipartFile) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            logger.error("上传的图片为null");
        }
        // 随机生成UUID
        String UUIDString = "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 4) + "_";
        // 获取用户目录
        String home = System.getProperty("user.home");
        // 获取当前日期
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 创建今日路径与文件最终位置
        File path = new File(home + "/JavaCode/sora-ui/public/pic/" + date);
        String fileName = "/source" + UUIDString + multipartFile.getOriginalFilename();
        File file = new File(path + fileName);
        if (!path.exists()) {
            path.mkdir();
        }
        BufferedImage bufferedImage = null;
        try {
            // 保存原始图片到本地
            multipartFile.transferTo(file);
            bufferedImage = ImageIO.read(file);
        } catch (IOException e) {
            logger.error("保存原始图片到本地出错 或 读取图片发生异常！");
        }

        // OCR识别图片文字
        InferenceEngine engine = InferenceEngine.getInstance(Model.ONNX_PPOCR_V3);
        OcrResult ocrResult = engine.runOcr(file.getPath());
        ArrayList<TextBlock> textBlocks = ocrResult.getTextBlocks();
        BufferedImage image = createImage(bufferedImage,textBlocks);

        try {
            // 保存结果图片到本地
            File output = new File(path + "/output" + UUIDString + multipartFile.getOriginalFilename());
            ImageIO.write(image, "png", output);
            // 响应图片到前端
//            response.setContentType("image/png");
//            ImageIO.write(image, "png", response.getOutputStream());
        } catch (IOException e) {
            logger.error("保存输出图片到本地出错 或 响应至前端发生异常！");
        }
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("url", "/pic/" + date + "/output" + UUIDString + multipartFile.getOriginalFilename());
        resultMap.put("text", ocrResult.getStrRes().trim());

        return Result.success(resultMap);
    }

    public static BufferedImage createImage(BufferedImage userImage, List<TextBlock> textBlocks) {
        // 获取用户上传图片的宽度和高度
        int width = userImage.getWidth();
        int height = userImage.getHeight();

        // 创建一个BufferedImage对象，使用用户上传图片的尺寸
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        // 从图片获取图形上下文
        Graphics2D g2d = image.createGraphics();

        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // 填充纯白背景
//        g2d.setColor(Color.WHITE);
//        g2d.fillRect(0, 0, width, height);

        // 在图片上绘制用户上传的图片
//        g2d.drawImage(userImage, 0, 0, null);

        // 设置文本的字体和颜色
        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font("宋体", Font.PLAIN, 16)); // 指定字体和大小，根据需要调整

        // 在图片上绘制每个文本块
        for (TextBlock block : textBlocks) {
            // 获取文本框的四个点
            ArrayList<Point> boxPoint = block.getBoxPoint();
            Point p1 = boxPoint.get(0);
            Point p2 = boxPoint.get(1);

            // 计算旋转角度
            double angle = Math.atan2(p2.getY() - p1.getY(), p2.getX() - p1.getX());

            String text = block.getText();

            // 在指定坐标处绘制文本
            AffineTransform orig = g2d.getTransform();
            g2d.rotate(angle, p1.getX(), p1.getY());
            g2d.drawString(text, p1.getX(), p1.getY());
            g2d.setTransform(orig);
        }

        // 释放图形上下文
        g2d.dispose();
        return image;
    }
}
